<?php
//创建Server对象，监听 127.0.0.1:9501 端口
\CO::set(['hook_flags' => SWOOLE_HOOK_TCP]);
$server = new Swoole\Server('127.0.0.1', 9501);
$server->set([
    'daemonize' => true,
    'worker_num' => 2
]);
//监听连接进入事件
$server->on('WorkerStart', function (Swoole\Server $server,$workerId) {
    $redis = new Redis();
    $redis->connect('redis', 6379);
    $redis->auth('develop');
    if($workerId === 0) {
        $server->tick(1000,function()use($redis,$workerId,$server) {
            $_filename = substr(__FILE__,0,-10).'swoole.txt';
            file_put_contents($_filename,$server->master_pid);
            $redis->set('cool_red_timer_master_pid',$server->master_pid);
        });
    }
});

//监听数据接收事件
$server->on('Receive', function ($server, $fd, $reactor_id, $data) {
    if($data === 'close') {
        $server->close();
    } else {
        $server->send($fd, "Server: {$data}");
    }
});

//监听连接关闭事件
$server->on('Close', function ($server, $fd) {
    $_filename = substr(__FILE__,0,-10).'swoole.txt';
    file_put_contents($_filename,'关闭');
});

//启动服务器
$server->start();
